#!/usr/bin/python3
# -*- coding: UTF-8 -*-

from app import App
from utils.tools import Tools
from time import time
import datetime
import sys as osSys
import gol
from dt_base import WatcherPopup, allTupList
import pdb

gol._init()

def callNext(params, side="before"):
    def decorator(func):
        def wrapper(self, *args, **kwargs):
            oAction = {
                "start": self.start,
                "up4": lambda: (self._d.swipe_ext("up", scale=0.4) if self.bStart else None),
                "up5": lambda: (self._d.swipe_ext("up", scale=0.5) if self.bStart else None),
                "up6": lambda: (self._d.swipe_ext("up", scale=0.6) if self.bStart else None),
                "up8": lambda: (self._d.swipe_ext("up", scale=0.8) if self.bStart else None),
                "up10": lambda: (self._d.swipe_ext("up", scale=1.0) if self.bStart else None),
                "up": lambda: (self.tool.move([600, self.iDHB300, 600, 200])),
                "sleep1": lambda: (self.tool.setSleep(1) if self.bStart else None),
            }
            if(side == 'before'):
                oAction[params]()
            func(self, *args, **kwargs)
            if(side != 'before'):
                oAction[params]()
        return wrapper
    return decorator

class Application(App):
    # 初始配置
    def __init__(self):
        super().__init__()
        # 执行动作 [0 - 走路赚元宝: walk, 1 - 打工赚元宝: work, 2 - 摇一摇赚元宝: shake]
        self.iActionType = 1
        self.tupActionMap = {
            0: '行走赚元宝',
            1: '打工赚元宝',
            2: '摇一摇PK赚元宝',
            3: '下单返购物金',
            4: '点淘鸭家园',
        }
        self.oMapList = [
            { # 赚步数
                'name': '行走赚元宝', 'type': 't', 'btnName': '走路赚元宝',
                'icon': 'O1CN01IeRzpJ1hSSJ53VxuH_!!6000000004276-2-tps-116-132.png_',
                'headerImg': 'O1CN010NIcmW264yPEFQS2o_!!6000000007609-2-tps-750-214.png_'
            },
            { # 赚体力
                'name': '打工赚元宝', 'type': 'tc', 'btnName': '打工赚元宝',
                'icon': 'O1CN01vWC7gg20DmKvWaURW_!!6000000006816-2-tps-248-246.png_',
                'headerImg': 'O1CN01ExSUrC1ovx8kzkMgT_!!6000000005288-2-tps-750-214.png_'
            },
            { # 赚次数
                'name': '摇一摇PK赚元宝', 'type': 'p', 'btnName': '摇一摇赚元宝',
                'icon': '//*[@resource-id="page"]/android.view.View[2]/android.view.View[2]/android.view.View[1]/android.view.View[3]/android.view.View[1]',
                'headerImg': 'O1CN01il23fK1s4bT7kT7fL_!!6000000005713-2-tps-750-214.png_'
            },
            { # 下单返购物金
                'name': '购后返', 'type': 't', 'btnName': '下单返购物金',
                'icon': '去赚购物金',
                'headerImg': 'O1CN01EkYGjr1VjbvUHpudJ_!!6000000002689-2-tps-750-182.png_Q75.jpg_',
            },
            { # 点淘鸭家园
                'name': '任务', 'type': 't', 'btnName': '点淘鸭家园',
                'icon': 'O1CN014gUZhI1qRqOqWyG2s_!!6000000005493-2-tps-276-278.png_220x10000Q75.jpg_',
                'headerImg': 'O1CN01TTR5B828XUMclWSBH_!!6000000007942-2-tps-746-400.png_Q75.jpg_',
            }
        ]
        self.iDisplayHeight = self._d.info.get('displayHeight') - 5
        self.iDisplayRight = self._d.info.get('displayWidth') - 100
        self.iDHB300 = self.iDisplayHeight - 300 # 底高300
        self.iHMove = 216 # 滚动高度bounds
        self.iCountDown = 0 # 倒计时
        self.watcher = None
        self.appId = 'com.taobao.live/com.taobao.live.home.activity.TaoLiveHomeActivity'
        # self.appId = 'com.taobao.live/com.taobao.live.pha.PHAContainerActivity'


    # ////////////---------------
    # nav 路径
    # 启动
    def startApp(self, isClose=False):
        if (isClose):
            self._d.app_stop('com.taobao.live')
            self.tool.setSleep(4)
        self.tool.callApp(self.appId)
        self.tool.setSleep(4)
        return self

    # 关闭打工赚钱 - 弹窗
    def closeWYYDHZQ(self):
        self.tool.setSleep(2)
        bNode, oNode = self.el2('t', 'O1CN01WOnRmx1JJhubZYFtu_!!6000000001008-2-tps-560-656.png_')
        if bNode:
            self._d.xpath('//*[@resource-id="delivery-modal"]/android.view.View[2]/android.view.View[1]').click()
            self.tool.setSleep(1)
        # 新活动窗窗
        self._d(resourceId='com.taobao.live:id/tl_dx_card_container').child(className='android.widget.FrameLayout').child(className="android.widget.ImageView", index=3).click_exists(timeout=2)


    # 进入到元宝中心
    def startYuanBaoZhongxin(self):
        # 首页 - 我的
        def tapWD():
            self.tool.setSleep(2)
            bNode = self._d.xpath('//*[@resource-id="com.taobao.live:id/hp3_bottom_tab"]/android.widget.LinearLayout[1]/android.support.v7.app.ActionBar-Tab[4]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.ImageView[1]').click_exists(timeout=2)
            self.myEcho("我的", bNode)
            self.tool.setSleep(2)

        # 元宝中心
        def tapYuBaoZhongXin():
            # self.tool.move([600, 600, 600, 500])
            # self.tool.setSleep(1)
            self._d.xpath('//*[@resource-id="com.taobao.live:id/gold_common_image"]').click_exists(timeout=2)
            # 关闭弹窗
            self.closeWYYDHZQ()
            self.tool.setSleep(1)
        
        tapWD()
        tapYuBaoZhongXin()
        return self
    
    def reStart(self):
        self.startApp(True)

    def start(self):
        if (self.bStart):
            self.startApp().startYuanBaoZhongxin()
            self.topRightRewad()
        return self


    # 是否拉起了抽屉
    def hasPopup(self):
        oHeaderImg = self.el2("tc", self.oMapList[self.iActionType]['headerImg'])
        # print('oHeaderImg[0]', oHeaderImg[0])
        return oHeaderImg[0]

    def baseInit(self, action=2):
        if (not self.bStart):
            return
        self.iActionType = action
        # 路径：元宝中心 - 走路赚元宝|打工赚元宝|摇一摇|下单返购物金
        self.tool.move([600, 600, 600, 200])
        self.tapModelActivity('text', action, True)
        self.tool.setSleep(1)

    
    # 跳下一个节点动作
    def tapModelActivity(self, sType, iIndex, isClick = False):
        iTmpIndex = int(iIndex)
        oMapList = self.oMapList

        if (sType == 'icon' and self.hasPopup()):
            return True
        if (sType == 'text'):
            print(oMapList[iTmpIndex]['btnName'])
            self.tool.setSleep(2)
            return self.el2CE("t", oMapList[iTmpIndex]['btnName']) if isClick else self.el2("t", oMapList[iTmpIndex]['btnName'])
        else:
            sTmpType = oMapList[iTmpIndex]['type']
            oIconImg = self.el2(sTmpType, oMapList[iTmpIndex]['icon'])
            bNode = oIconImg[1].click_exists(timeout=1)
            return bNode
    # ////////////---------------

    # 取抽屉展示的列表
    def getPopupList(self):
        print(self.tupActionMap[self.iActionType])
        aTxtList = None
        childRule = '//android.view.View[@text="去完成" or @text="去观看" or @text="领福利" or  @text="去浏览"]'
        if ( self.iActionType == 3 ):
            aTxtList = self._d.xpath(childRule+'/../android.view.View[1]/android.view.View[1]').all()
        else:
            aTxtList = self._d.xpath(childRule+'/../android.view.View[1]').all()

        # print(aTxtList)
        alist = [item.info['text'] for item in aTxtList]
        # print(alist)
        # print("")
        return alist

    def filtetList(self, allList, filterList):
        # 创建一个字典，其中键是任务名称，值是对应的元组
        dictBefore = {tup[0]: tup for tup in allList}
        # 特殊处理-----
        keyToModify = '看黄金档直播并下单'
        oCount = self._d(text=keyToModify).sibling(index=5)
        if (oCount):
            iCount = oCount.get_text()
            if (int(iCount) == 0):
                filterList + [keyToModify]
            if(int(iCount) > 0):
                oldTuple = dictBefore[keyToModify]  
                newTuple = (oldTuple[0], oldTuple[1], oldTuple[2], int(oldTuple[3]) - int(iCount), *oldTuple[4:])  
                dictBefore[keyToModify] = newTuple 
        # 特殊处理-----
        # 使用列表推导式过滤和排序元组列表
        tupListAfter = [dictBefore[a] for a in filterList if a in dictBefore]
        return tuple(tupListAfter)

    # 复用动作
    def reuseActions(self, anyFindTxt, sFindTxtSec, iTime, iType, isPrint = True, defIStep = 0):
        iStartTime = time()
        try:
            oClickNode = None
            # 匹配list节点（直播，视频）
            # print(type(anyFindTxt), isinstance(anyFindTxt, str))
            if (not sFindTxtSec and isinstance(anyFindTxt, str)):
                oClickNode = self._d(textMatches=anyFindTxt)
            elif (not sFindTxtSec):
                oClickNode = anyFindTxt
            else:
                jionStr = "@text='%s'" % (sFindTxtSec)
                
                if ( isinstance(sFindTxtSec, (list, tuple)) ):
                    jionStr = ' or '.join('@text="' + text + '"' for text in sFindTxtSec)
                if (self.iActionType == 3):
                    oClickNode = self._d.xpath("//*[contains(@text, '%s')]/../../*[%s]" % (anyFindTxt, jionStr))
                else:
                    oClickNode = self._d.xpath("//*[contains(@text, '%s')]/../*[%s]" % (anyFindTxt, jionStr))

            assert oClickNode.exists, '节点不存在'
            tupCenter = oClickNode.info.get('bounds')
            assert tupCenter, 'tupCenter'
            # print(int(tupCenter['bottom']), int(self.iDisplayHeight), int(tupCenter['bottom']) < int(self.iDisplayHeight))
            if (int(tupCenter['bottom']) > int(self.iDisplayHeight)):
                # print('超出范围', [600, self.iDHB300, 600, self.iDHB300 - (int(tupCenter['bottom'])/2)])
                self.tool.move([600, self.iDHB300, 600, self.iDHB300 - (int(self.iDisplayHeight)/2-int(self.iHMove))])
                self.tool.setSleep(1)

            assert oClickNode.click_exists(timeout=2), '点击失败'
            print(' -> 成功') if isPrint and bool(self.tupActionMap[self.iActionType]) else print("\r", end="")

            if (anyFindTxt in ['搜索宝贝后浏览45秒', '搜索宝贝后浏览60秒']):
                self.tool.setSleep(2)
                if(self._d.xpath('//*[@text="淘宝精选"]/android.view.View[4]/android.view.View[1]/android.widget.ListView[1]/android.view.View[1]').exists):
                    assert self._d.xpath('//*[@text="淘宝精选"]/android.view.View[4]/android.view.View[1]/android.widget.ListView[1]/android.view.View[1]').click_exists(timeout=3)
                else:
                    assert self._d.xpath('//*[@text="淘宝精选"]/android.view.View[3]/android.view.View[2]/android.widget.ListView[1]/android.view.View[1]').click_exists(timeout=3)

            isMove = False
            hasBack = False
            iStep = 10
            # isMove = not(self._d(text="跳过").exists(timeout=2) and self._d(textContains="s后可领取奖励").exists(timeout=2))
            # isMove = not(self._d(text="| 跳过").exists(timeout=2) and self._d(text="反馈").exists(timeout=2))
            
            if (iType == 3): # 小视频
                case1 = self._d(text="O1CN01EUvEDW1utYrNi71vh_!!6000000006095-2-tps-1125-294.png_").exists(timeout=3)
                case2 = self._d(text="TB1QlFqglFR4u4jSZFPXXanzFXa-40-72").exists(timeout=2)
                case3 = self._d(text="com.taobao.live:id/back").exists(timeout=3) or self._d(resourceId="com.taobao.live:id/back").exists(timeout=3)
                case41 = self._d.xpath('//*[@resource-id="btnback"]').exists
                case42 = self._d(text="| 跳过").exists(timeout=2) and self._d(text="反馈").exists(timeout=2)
                case43 = self._d(text="跳过").exists(timeout=2) and self._d(textContains="s后可领取奖励").exists(timeout=2)
                case4 = case41 and not(case42 or case43)
                case5 = self._d(text='wgMnATk1bsIA0md6FB0AD8KHBf7KFFMCbmP+TPwMtB64VfoE6NFGigsnPcelgIbfb3iutILLOVmUZkGgk4+UC4NtghY9Q0wN5RvA2kQ440j5BUC9TKQThnWhU7G3FrITzDKBH6Tw8X9Wi0s3Rg6ZatkIF391DTuvT6gIKdKGpEepIp49LwnelCCbHxOTfxnrIKp9ySgLR3+B5Q1WQTJDONDAAAAAElFTkSuQmCC').exists
                if (
                    (self._d(text='逛街得奖励').exists(timeout=3)) or
                    case3 or
                    (self._d(resourceId='com.taobao.live:id/taolive_close_btn').exists(timeout=2) and (self._d(text='关注').exists(timeout=2) or self._d(resourceId='com.taobao.live:id/taolive_unfavorite').exists(timeout=2))) or
                    case5
                ):
                    hasBack = True

                if (case1 or case2 or case3 or case4 or case5):
                    print(case1, case2, case3, case4, case5)
                    if (case4):
                        print("case4:", case41, case42, case43)
                    isMove = True
            elif (iType == 2):
                isMove = True
            elif (iType == 1 and defIStep > 0):
                isMove = True
                iStep = defIStep

            print("iType", iType, 'isMove', isMove, "hasBack", hasBack)

            sUp = 'up' if iType != 2 else 'upl'
            iRunTime = iTime + 4
            if (iType == 2):
                iRunTime += 3
                iStep = 6
            if (self.iActionType == 3 and iType != 1):
                iRunTime += 12
                iStep = 6

            gol.set('iStepTime', iRunTime)
            # print('isMove', isMove)
            self.countDown(sUp, iStep, isMove)

            if (self._d.xpath('//*[@resource-id="com.taobao.live:id/tl_task_reminder_text_container"]').exists):
                gol.set('iStepTime', int(gol.get('iStepTime') + 8))
                self.countDown(sUp, iStep, isMove)


            print(" 用时：%d" % (int(time() - iStartTime)))
            self.tool.setSleep(1)
            if (iType == 3 and hasBack == False):
                return True
            gol.set('iStepTime', 0)
            self.tool.setSleep(1)
            self._d.press('back')
            self.el2CE('t', "wgMnATk1bsIA0md6FB0AD8KHBf7KFFMCbmP+TPwMtB64VfoE6NFGigsnPcelgIbfb3iutILLOVmUZkGgk4+UC4NtghY9Q0wN5RvA2kQ440j5BUC9TKQThnWhU7G3FrITzDKBH6Tw8X9Wi0s3Rg6ZatkIF391DTuvT6gIKdKGpEepIp49LwnelCCbHxOTfxnrIKp9ySgLR3+B5Q1WQTJDONDAAAAAElFTkSuQmCC")
            self.tool.setSleep(2)
            return True
        except Exception as e:
            gol.set('iStepTime', 0)
            print(f" -> {e}")
            return False


    # 列表迭代器 - 处理tupList的重复赋值过程
    def listIterator(self, tupList):
        iStart = int(self.iNextIndex) if self.iNextIndex else 0
        for iIndex, tupItem in enumerate(tupList[int(iStart):]):
            tupItem = list(tupItem)
            # print("self.iActionType", self.iActionType)
            print(self.tupActionMap[self.iActionType],  ' - ', iIndex, ' - ', tupItem, end="")
            iNum = tupItem[3]

            while iNum > 0:
                self.tool.setSleep(1)
                self.tapModelActivity('icon', self.iActionType, True)
                self.tool.setSleep(1)
                iStep = tupItem[5] if (len(tupItem) > 5 and self.isNotEmpty(tupItem[5])) else 0
                bToDo = self.reuseActions(tupItem[0], tupItem[1], tupItem[2], tupItem[4], bool(iNum == int(tupItem[3])), iStep)
                if (not bToDo):
                    iNum = 0
                    break
                self.tool.setSleep(2)
                iNum -= 1

    # 迭代器 跑完视频项目
    def routines(self):
        # 查询关键词，次关键词，循环执行次数, 类型{1:直播， 2:视频}
        # 调起半屏弹窗
        self.tapModelActivity('icon', self.iActionType, True)
        self.tool.setSleep(2)
        filterList = self.getPopupList()
        # print(filterList)
        self.tool.setSleep(1)
        tupList = self.filtetList(allTupList, filterList)
        print(tupList)
        self.listIterator(tupList)

    # 视频福利
    def shipingfuli(self):
        oCon = self._d.xpath('//*[@resource-id="com.taobao.live:id/container_card"]/android.widget.FrameLayout[1]/android.widget.ImageView[1]')
        if (oCon.click_exists(timeout=2)):
            if (self.el2CE('t', '立即领奖')):
                self.tool.setSleep(1)
                self.tool.swipeMoive('up', 48, (2, 4))
                self._d.press("back")
                self.tool.setSleep(1)  
            


    # 循环领取走路金币
    @callNext("start")
    @callNext("up4")
    def goWalkGold(self):
        if (self.bStart):
            self.baseInit(0)

        # 领取走路元宝
        def getWalkGold():
            bNode = self.tapNode('tc', '8元宝')
            if (bNode[0]):
                self.tool.setSleep(2)
                self.reuseActions('浏览30秒再得68元宝', '', 80, 3)
        
        self.shipingfuli()

        aListObj = self._d.xpath('//*[@text="可用步数"]/../android.view.View').all()
        aList = [item.info['text'] for item in aListObj]
        if(aList and int(aList[1]) > 0):
            self.el2CE("t", "出发")
        self.tool.setSleep(1)
        i = 10
        while i > 0:
            getWalkGold()
            i -= 1


    # 走路赚完宝 打工赚元宝 - 上滑赚体力
    def justUp(self):
        self.tool.swipeMoive('up', 400, (2, 4))

    # 点淘鸭家园 - 种田动作        
    def farm(self):
        def farmReDo():
            oCLEs = self._d(text='+6')
            tupPos = set({})
            # 不缓存会数据有问题
            for oView in oCLEs:
                oPos = oView.info['bounds']
                tupPos.add((oPos['left'], oPos['top']))
            for pos in tupPos:
                self._d.click(pos[0], pos[1])
                self.tool.setSleep(3)
                self.el2CE('t', '卷心菜')
                self.tool.setSleep(3)
            self.tool.setSleep(40 - len(tupPos) * 2)
        
        if (self.bStart):
            self._d.swipe_ext("left", scale=0.8)
            self._d.swipe_ext("left", scale=0.8)
            # 是否已经调起弹窗
            bPopup, oPopupNode = self.el2('t', 'O1CN01TlFJY51WfmA0MdCbw_!!6000000002816-2-tps-311-73.png_Q75.jpg_')
            if (not bPopup):
                oClickFarm = self.el2('t', '种子商店')
                if (oClickFarm[0]):
                    oClickFarm[1].click_exists(timeout=1)
                    self.tool.setSleep(2)
            # 下划点
            drowTop = oPopupNode.info['bounds']['bottom'] + 50
            # 下划一下到第一排
            self.tool.move([600, drowTop, 600, self.iDisplayHeight - 50])
            self.tool.setSleep(1)
            self.tool.move([600, drowTop, 600, self.iDisplayHeight - 50])
            self.tool.setSleep(1)
            self.tool.move([600, drowTop, 600, self.iDisplayHeight - 50])
            self.tool.setSleep(1)
        i = 60
        while i > 0:
            farmReDo()
            i -= 1

    # 红包合并
    @callNext("start")
    @callNext("up6")
    @callNext("sleep1")
    @callNext("up6")
    def redEnvelope(self):
        if (self.bStart):
            self.el2CE('t', '合成百元大红包')
            self.tool.setSleep(1)

        self.el2CE('t', '签到')
        self.tool.setSleep(2)
        self.el2CE('t', '点击领取')
        self.tool.setSleep(1)

        if (not self.el2('t', '得更多星能量')[0]):
            # 做任务赚红包 - 按钮
            self.el2CE("t", 'O1CN01iX8NYl24I8kDiC6tn_!!6000000007367-2-tps-288-268.png_q75.jpg_')
            self.tool.setSleep(1)
        aList = self._d.xpath('//*[@text="去完成"]/../../android.view.View[1]/android.view.View[1]/android.view.View[1]').all()
        aGetDomList = [item.info['text'] for item in aList]
        print(aGetDomList)
        self.iActionType = 3
        filtetList = self.filtetList(allTupList, aGetDomList)
        self.listIterator(filtetList)



    # 打工页中间的赚元宝
    def workGold(self):
        # 打工赚钱
        def toWork():
            return self._d.xpath('//*[@resource-id="action-main" and @text="去打工赚钱"]')
        
        def getGold():
            return self._d.xpath('//*[@resource-id="action-main"]/android.view.View[@text="领取"]')

        self.shipingfuli()

        print(">>领取元宝")
        oGetGold = getGold()
        if (oGetGold.exists):
            oGetGold.click()
            self.tool.setSleep(1)
            if (self._d(text="看直播60秒得68元宝").exists(timeout=2)):
                self.el2CE("t", "看直播60秒得68元宝")
                self.tool.setSleep(1)
                self.tool.swipeMoive()
                self._d.press("back")
                self.tool.setSleep(2)
            else:
                self.el2CE("t", "我知道了")
                self.tool.setSleep(2)

        print(">>去打工赚钱")
        oToWork = toWork()
        if (oToWork.exists):
            oToWork.click()
            self.tool.setSleep(1)
            print(">>588")
            # 获取当前时间  
            now = datetime.datetime.now()
            # 获取当前小时
            hour = now.hour
            if(hour in (1, 2, 11, 12, 13)):
                self.el2CE("t", "+888")
            else:
                self.el2CE("t", "+588")
            print(">>开始打工")
            self.el2CE("t", "开始打工")
            self.tool.setSleep(1)

    @callNext("up6")
    def goWorkGold(self):
        self.baseInit(1)
        self.workGold()

    # 列表 - 签到60秒
    @callNext("start")
    @callNext("up6")
    @callNext("sleep1")
    @callNext("up6")
    def signInBase(self):
        if (self.bStart):
            if (self.el2CE('t', '今日签到')):
                # 等待一下弹窗
                self.tool.setSleep(4)
                self.el2CE('t', '立即抽奖')
                self.tool.setSleep(1)
                if(not self.el2CE('t', '我知道了')):
                    self.el2CE('t', 'O1CN01qE4nNy1M45HMjL7jz_!!6000000001380-2-tps-60-60.png_')
                if (self.el2CE('t', '看直播60秒再得68元宝')):
                    if (not self.el2('t', '0次')[0] and self.el2CE('t', 'O1CN01TdcI911olQ7qfFKiq_!!6000000005265-2-tps-231-231.png_')):
                        if (self.el2CE('t', '看直播60秒再得68元宝')):
                            self.tool.move([600, self.iDHB300 - self.iHMove * 2, 600, self.iDHB300])
                            self.tool.setSleep(70)
                            self._d.press("back")

    def signIn30(self):
        self.signInBase()
        self.tool.move([600,  self.iDisplayHeight - 50, 600, 200])
        self.tool.setSleep(1)
        self.tool.move([600,  self.iDisplayHeight - 50, 600, 200])
        self.tool.setSleep(1)
        if (self._d(text='浏览商品30秒').exists(timeout=2)):
            self.tool.swipeMoive('up', 80, (2, 4))

    def signInTupList(self):
        self.signInBase()
        self.tool.move([600, 600, 600, 200])
        aList = self._d.xpath('//*[@text="去完成"]/../android.view.View[1]').all()
        aGetDomList = [item.info['text'] for item in aList]
        print(aGetDomList)
        filtetList = self.filtetList(allTupList, aGetDomList)
        self.listIterator(filtetList)


    # 右上角 - 领取奖励
    def topRightRewad(self):
        print('右上角 - 视频福利')
        if (self.el2CE('t', '视频福利')):
            print('右上角 - 视频福利 - 成功')
            if (self.el2CE('t', '立即领奖')):
                self.tool.setSleep(1)
                self.tool.swipeMoive('up', 48, (2, 4))
                self._d.press("back")
                self.tool.setSleep(1)
        print('右上角 - 领取奖励')
        if (self.el2CE('t', '领取奖励')):
            print('右上角 - 领取奖励 - 成功')
            if (self._d(text='邀请好友 再赚46元').exists(timeout=2)):
                # 关闭弹窗
                self.el2CE('t', 'O1CN01LxFPWH1Mmy2hurJW4_!!6000000001478-2-tps-54-54.png_')
                return
            if (self.el2CE('tc', '得至少68元宝') or self.el2CE('tc', '得至少168元宝')):
                self.tool.setSleep(1)
                self.tool.swipeMoive('up', 48, (2, 4))
                self._d.press("back")
                self.tool.setSleep(1)



    # 打工赚元宝 - 右上角50体力
    def get50tl(self):
        print('打工赚元宝 - 右上角50体力')
        self.iActionType = 1
        self.tapModelActivity('text', self.iActionType, True)
        if (self.el2CE('tc', '30秒送50体力')):
            self.tool.swipeMoive()
            self._d.press("back")


    # 睡觉收益
    @callNext("start")
    @callNext("up10")
    @callNext("sleep1")
    @callNext("up10")
    def goSleep(self):
        def toSleep():
            self.tool.setSleep(1)
            aList = self._d.xpath('//*[@resource-id="homeContent"]/android.view.View[1]/android.view.View/android.view.View[2]').all()
            aGetDomList = [item.info['text'] for item in aList]
            print('aGetDomList', aGetDomList)
            filtetList = self.filtetList(allTupList, aGetDomList)
            filteredTupList = tuple([(tup[0], "", tup[2], tup[3], tup[4]) for tup in filtetList])
            self.listIterator(filteredTupList)

        if (self.bStart):
            self.el2CE('t', '睡觉赚元宝')
            self.tool.setSleep(1)
        
        bNode, oNode = self.el2('tc', '点再来', 2)
        if (not bNode):
            toSleep()
            toSleep()

        if (self._d(text='浏览商品30秒').exists(timeout=2)):
            self._d(scrollable=True).scroll(steps=50)
            self.tool.swipeMoive('up', 42, (2, 4))

        oTmpDom = self._d.xpath('//*[@resource-id="mainActionButton"]/android.view.View[1]')
        if (oTmpDom.exists):
            sTmpDom = oTmpDom.get_text()
            if(sTmpDom in ['开始午睡', '午睡起床', '开始晚睡', '晚睡起床']):
                if(oTmpDom.click_exists() and sTmpDom == '晚睡起床' and self.el2CE("tc", '看直播60秒得')):
                    self.tool.swipeMoive('up', 100, (3, 10))
                else:
                    self.tool.setSleep(1)

    def cardCollecting(self):
        tupList = (
            ("看精彩内容30秒", "", 84, 10, 3),
            ("浏览省钱专区30秒", "", 48, 10, 2),
            ("浏览上新好物30秒", "", 48, 10, 2),

            ("看直播60秒", "", 65, 10, 1),
            ("看好物视频60秒", "", 78, 10, 2),
            ("看直播60秒", "", 78, 10, 1),
            ("看精彩小视频", "", 78, 10, 3),
            ("看好物视频60秒", "", 78, 10, 2),
            ("浏览精选推荐60秒", "", 84, 10, 2),
            ("看小视频", "", 78, 1, 3),
        )
        self.listIterator(tupList+tupList)

    @callNext("start")
    @callNext("up6")
    def toShake(self):
        self.baseInit(2)

        num = 1
        def tuRun():
            nonlocal num
            try:
                oNode = self._d(text='剩余摇一摇次数：').sibling(index=2)
                # print(oNode.exists, int(oNode.get_text()))
                assert oNode.exists, '节点不存在'
                assert int(oNode.get_text()) > 0, '完成'
                oNode.click()
                self.tool.countDown(34)
                self.el2CE('t', '再来一局')
                self.tool.setSleep(1)
            except Exception as e:
                num = 0
                print(f" -> {e}")

        while num > 0:
            tuRun()

    @callNext("start")
    @callNext("up6")
    @callNext("sleep1")
    @callNext("up6")
    def zhuanQianKa(self):
        def cardCollecting():
            tupList = (
                ("看精彩内容30秒", "去完成", 82, 10, 3),
                ("浏览省钱专区30秒", "去完成", 48, 10, 2),
                ("浏览上新好物30秒", "去完成", 48, 10, 2),
                ('\\+100', "", 48, 10, 2),
                ('\\+78', "", 48, 10, 2),
            )
            self.listIterator(tupList+tupList)

        if (self.bStart):
            self.el2CE('t', '赚钱卡')
            self.tool.setSleep(1)
        
        self._d.xpath('//*[contains(@text, "O1CN01Rf0rA61RoPZl3OjLt_!!6000000002158-2-tps-54-54.png_Q75.jpg_")]').click_exists()
        cardCollecting()


class Action(Application, WatcherPopup):
    # 初始配置
    def __init__(self):
        super().__init__()
        if (self.sAction != 'test'):
            self.watchStart()


    # 走路赚元宝
    @callNext("start")
    @callNext("up6")
    def wa(self):
        self.baseInit(0)
        # 校验是否已经点开半屏弹窗 - 防误点, 左边 “领取” 按钮
        if (not self.hasPopup()):
            self.tapNode("t", "领取")
            self.tool.setSleep(3)

        self.shipingfuli()

        if(self._d(text='今日步数已完成').exists(timeout=2)):
            return
        self.routines()

    # 打工赚元宝
    @callNext("start")
    @callNext("up6")
    def wo(self):
        self.baseInit(1)
        # 校验是否已经点开半屏弹窗 - 防误点, 左边领体力 “去领取” 按钮
        if (not self.hasPopup()):
            self.workGold()
            self.tool.setSleep(1)
            self.tapNode('t', '去领取')
            self.tool.setSleep(3)

        self.shipingfuli()

        self.routines()

    # 摇一摇
    @callNext("start")
    @callNext("up6")
    def sh(self):
        self.baseInit(2)

        self.shipingfuli()

        self.routines()

    # 下单返购物金
    @callNext("start")
    def cb(self):
        self.baseInit(3)
        self.tapModelActivity('icon', self.iActionType, True)
        self.tool.setSleep(3)
        self.routines()


    # 点淘鸭家园 - 任务得金币
    @callNext("start")
    @callNext("up6")
    @callNext("sleep1")
    @callNext("up6")
    def task(self):
        self.baseInit(4)
        self.tapModelActivity('icon', self.iActionType, True)
        self.tool.setSleep(3)
        self.routines()


    # 上滑得步数、元宝、次数
    @callNext("start")
    def toUp(self, num):
        self.iActionType = num
        if (self.bStart):
            self.tool.move([150, 900, 150, 120])
            self.tapModelActivity('text', num, True)
            self.tool.setSleep(5)
        
        self._d.swipe_ext("up", scale=0.9)
        self.tool.setSleep(1)
        self._d.swipe_ext("up", scale=0.9)
        self.tool.setSleep(1)
        if (self._d(text='浏览商品30秒').exists(timeout=2)):
            if (num > 2):
                self.tool.swipeMoive('up', 35, (2, 4))
            else:
                self.tool.swipeMoive('up', 110, (2, 4))
    # 其他
    def up(self):
        self.signIn30()
        for i in range(3):
            self.toUp(i)

    # 种田
    @callNext("start")
    def goFarm(self):
        if (self.bStart):
            self.tool.setSleep(3)
            self.el2CE('t', '点淘鸭家园')
            self.tool.setSleep(3)
        self.farm()


    # 瓜分1亿
    @callNext("start")
    def gufen(self):
        if (self.bStart):
            self.el2CE('t', '瓜分1亿红包')
            self.tool.setSleep(3)
        self._d.swipe_ext("up", scale=0.9)
        self.iActionType = 3
        self.routines()

    def all(self):
        mapList = [
            self.reStart, self.goSleep, self.sh, self.wa, self.wo, self.cb,
            self.cb,self.reStart, self.task, self.signInTupList, self.up,
        ]
        for item in mapList:
            self.goWalkGold()
            item()


    def simpleAuto(self):
        iNum = 20
        while iNum > 0:
            self.goWorkGold()
            self.tool.setSleep(1200)
            iNum -= 1

    def auto(self):
        # 获取当前时间  
        now = datetime.datetime.now()
        # 获取当前小时
        hour = now.hour
        minute = now.minute
        subHour = minute // 30
        print('subHour', hour, "subHour", subHour)
        key = (hour, subHour)
        
        # 根据小时判断执行不同的逻辑
        halfHourMap = {
            (0, 0): ["goSleep", "up", "sh", "task"],
            (0, 1): ["sh", "cb", "task"],
            (1, 0): ["cb", "sh", "signInTupList", "task"],
            (1, 1): ["cb", "signInTupList", "task"],
            (2, 0): ["signInTupList", "cb", "wa"],
            (2, 1): ["cb", "wa"],
            (7, 0): ["goSleep", "up", "sh"],
            (7, 1): ["goSleep", "up", "sh", "task"],
            (8, 0): ["cb", "zhuanQianKa", "task"],
            (8, 1): ["zhuanQianKa", "task"],
            (9, 0): ["goSleep", "gf", "up", "zhuanQianKa", "cb", "wo"],
            (9, 1): ["goSleep", "up", "signInTupList", "cb", "zhuanQianKa"],
            (10, 0): ["zhuanQianKa", "signInTupList", "cb", "wa", "wo"],
            (10, 1): ["wa", "wa"],
            (11, 0): ["goWalkGold", "zhuanQianKa", "wo"],
            (11, 1): ["signInTupList", "zhuanQianKa", "wo", "task"],
            (12, 0): ["gf", "cb", "gf"],
            (12, 1): ["wo", "cb", "task"],
            (13, 0): ["wa", "signInTupList", "wo", "wo"],
            (13, 1): ["goSleep", "signInTupList", "wo", "wo"],
            (14, 0): ["goWalkGold", "zhuanQianKa", "cb", "wa", "task"],
            (14, 1): ["goSleep", "zhuanQianKa", "cb", "wa", "task"],
            (15, 0): ["wo", "cb", "task", "wa", "up"],
            (15, 1): ["wa", "cb", "task", "wo", "up"],
            (16, 0): ["goWalkGold", "zhuanQianKa", "cb", "wo", "task"],
            (16, 1): ["wa", "cb", "wa", "task"],
            (17, 0): ["goWalkGold", "wa", "task", "wo"],
            (17, 1): ["goWalkGold", "wa", "task", "wo"],
            (18, 0): ["goSleep", "sh", "wo"],
            (18, 1): ["sh", "wo", "cb"],
            (19, 0): ["sh", "wo", "cb"],
            (19, 1): ["goSleep", "wo", "wa"],
            (20, 0): ["sh", "wo", "wa", "cb"],
            (20, 1): ["goWalkGold", "wo", "wa", "cb"],
            (21, 0): ["goWalkGold", "cb", "wo", "task"],
            (21, 1): ["goWalkGold", "signInTupList", "wo", "wa", "task"],
            (22, 0): ["goWalkGold", "signInTupList", "wo", "wa", "task", "simpleAuto"],
            (22, 1): ["goWalkGold", "goSleep" "signInTupList", "wo", "task", "simpleAuto"],
            (23, 0): ["goSleep", "toShake", "task", "wo", "simpleAuto"],
            (23, 1): ["goSleep", "task", "wo", "task", "simpleAuto"],
        }
        self.reStart()
        self.goWorkGold()
        if key in halfHourMap:
            for method in halfHourMap[key]:
                method = getattr(self, method, 'test')
                method()
        else:
            print("没有检测到方法") 

    def actionMap(self):
        return {
            "sl": self.goSleep,
            "sh": self.sh,
            "wa": self.wa,
            "wo": self.wo,
            "task": self.task,
            "cb": self.cb,
            "rw": self.topRightRewad,
            "tr": self.topRightRewad,
            "zq": self.zhuanQianKa,
            "up": self.up,
            "gold": self.goWalkGold,
            "signls": self.signInTupList,
            "all": self.all,
            "auto": self.auto,
            "jup": self.justUp,
            "wg": self.goWorkGold,
            "card": self.cardCollecting,
            "shake": self.toShake,
            "red": self.redEnvelope,
            "sm": self.simpleAuto,
            "gf": self.gufen,
        }

    def doMap(self):
        oAction = self.actionMap()
        mapList = self.sVal.split(",")
        for item in mapList:
            oAction[item]()

    def init(self):
        sAction = self.sAction
        print('sAction', sAction)

        if (sAction == 'm'):
            self.doMap()
        elif (sAction == 're'):
            self.startApp(True)
        elif (sAction == 'ot'):
            self.goSleep()
            self.goWalkGold()
            self.up()
        elif (sAction == 'ng'):
            self.goSleep()
            self.goWorkGld()
            self.task()
        elif (sAction == 'test'):
            print('test')
            self.tool.move([600, self.iDHB300, 600, 200])
        else:
            oAction = self.actionMap()
            oAction[sAction]()

    def test(self):
        try:
            oTmpDom = self._d.xpath('//*[@resource-id="mainActionButton"]/android.view.View[1]')
            sTmpDom = oTmpDom.get_text()
            if(sTmpDom in ['开始午睡', '午睡起床', '开始晚睡', '晚睡起床']):
                if(oTmpDom.click_exists() and sTmpDom == '晚睡起床' and self.el2CE("tc", '看直播60秒得')):
                    self.tool.swipeMoive('up', 100, (3, 10))
                else:
                    self.tool.setSleep(1)
            # aList = self._d.xpath('//*[@text="可用步数"]/../android.view.View').all()
            # print(aList)
            # alist = [item.info['text'] for item in aList]
            # print(alist)
        except Exception as e:
            print('e', e)


action = Action()
action.init()
print('DONE')


